import os

from flask import g
from flask import request
from flask.ext.classy import FlaskView, route

from ..services.offer import OfferService
from ..schema.error import FILE_ERROR, success
from ..services.resource import ResourceService
from ..schema.param import ticket_param


class OfferView(FlaskView):
    @route('/', methods=['POST'])
    def create_inventory(self):
        data, _ = ticket_param.load(request.get_json())
        price = data.pop('price')
        product_id = data.pop('product_id')
        recommded = data.pop('recommded')
        stock_info = data.pop('stock_info')
        mode = stock_info.pop('mode')
        resource_id = stock_info.pop('resource_id')
        mask = data.pop('mask')
        if mode == 'resource':
            resource = ResourceService.get_by_id(id=resource_id)
            if resource:
                file_path = resource.path
                f = open(file_path, 'r')
                key_lines = f.readlines()
                count = len(key_lines)
                offer_id = create_offer(product_id, count, price, mask)
                if os.path.exists(file_path) and len(file_path) > 0:
                    for value in key_lines:
                        ticket = OfferService.create_ticket(offer_id, value)
                if ticket:
                    return success.jsonify()
                else:
                    return FILE_ERROR.jsonify()
        elif mode == 'test':
            keys = stock_info.pop('keys')
            count = len(keys)
            offer_id = create_offer(product_id, count, price, mask)
            for value in keys:
                ticket = OfferService.create_ticket(offer_id, value)
            if ticket:
                return success.jsonify()
            else:
                return FILE_ERROR.jsonify()


def create_offer(product_id, count, price, mask):
    offer = OfferService.create_offer(product_id=product_id,
                                      count=count,
                                      price=price,
                                      mask=mask,
                                      dealer_id=g. user_id
                                      )
    return offer
